/*
* Global variables
*/

// is background process running?
var isRunning;
var RES_IMAGES_PREFIX = "Images/";
var MAX_WIDTH = 315;			// maximum width of tx_traffic item
var OFFSET = 0						/* 8 */;

// option name, option id, limit in MB
var PACKS = new Array(
	{display: "MINIMUM", name: "minimum", max: 250*1024},
	{display: "MEDIUM", name: "medium", max: 250*1024},
	{display: "EXTREME", name: "extreme", max: 250*1024},
	{display: "PROFESSIONAL", name: "pro", max: 250*1024}
);
var PACK_DEFAULT = 2;

var last_traffic = null;
var	current_ver = null;



function load()
{
	// put your setup code here...
	isRunning = false;

	// init chello packs popup options
	box = document.getElementById('chello_popup');
	p = getDefaultPack();
	
	for(i=0;i<PACKS.length;i++)
	{
		box.options[i] = new Option(PACKS[i].display, PACKS[i].name, (p == PACKS[i].name));
	}

	// set version
	current_ver = widget.system('/usr/bin/ruby read_ver.rb', null).outputString;
	document.getElementById("ver_label").innerText = "ChelloTraffic " + current_ver;

	reset();

	doMainTask();
}

function remove()
{
	// your widget has just been removed from the layer
	// remove any preferences as needed
	// widget.setPreferenceForKey(null, "your-key");
}

function hide()
{
	// your widget has just been hidden stop any timers to
	// prevent cpu usage
}

function show()
{
	// your widget has just been shown.  restart any timers
	// and adjust your interface as needed
}

function showBack(event)
{
	// your widget needs to show the back

	var front = document.getElementById("front");
	var back = document.getElementById("back");

	if (window.widget)
		widget.prepareForTransition("ToBack");

	front.style.display="none";
	back.style.display="block";
	
	if (window.widget)
		setTimeout('widget.performTransition();', 0);


	// my code
	if (window.widget) {
		var val;

		val = widget.preferenceForKey('id');
		if (val != null)
		document.getElementById("name_input").value = val;

		val = widget.preferenceForKey('pwd');
		if (val != null)
		document.getElementById("pwd_input").value = val;
	}
}

function showFront(event)
{
	// your widget needs to show the front

	var front = document.getElementById("front");
	var back = document.getElementById("back");

	if (window.widget)
		widget.prepareForTransition("ToFront");

	front.style.display="block";
	back.style.display="none";
	
	if (window.widget)
		setTimeout('widget.performTransition();', 0);
}




/*
* My Functions
*/

function doMainTask() {
	getTraffic();
	checkNewVersion();
}



function getTraffic()
{
	if (isRunning == false) {
		// reset widgets
		reset();

		cid = widget.preferenceForKey('id');
		pwd = widget.preferenceForKey('pwd');
		if (cid != null && pwd != null && cid.length > 0) {
			// start anim
			startRefreshAnim();

			isRunning = true;

			// execute ruby robot to get the traffic
			widget.system('/usr/bin/ruby traffic.rb ' + cid + ' ' + pwd, cmd_handler);
		} else {
			document.getElementById('tx_traffic').innerText = "HIBA: Kitöltetlen név vagy jelszó!";
		}
	} else {
		if (last_traffic != null) {
			setTraffic(last_traffic);
		} else {
			// reset widgets
			reset();
		}
	}
}

function cmd_handler(result)
{
	isRunning = false;

	var r = result.outputString;
	
	if (r == null) {
		// CRASH: call of external script failed
		document.getElementById('tx_traffic').innerText = "HIBA: belső hiba..";
	} else {
		// parse output
		var v = r.match(/^err:(\w+)/)

		if (v != null) {
			switch (v[1]) {
				case "login":
					document.getElementById('tx_traffic').innerText = "HIBA: Rossz név vagy jelszó.";
					break;
				case "failed":
					document.getElementById('tx_traffic').innerText = "HIBA: Érvénytelen adatkérés.";
					break;
				default:
					document.getElementById('tx_traffic').innerText = "Ismeretlen hiba.";
					break;
			}
		} else {
			var n = parseInt(r);
			last_traffic = n;
			setTraffic(n);
		}
	}


	// stop anim
	// FIXME: should this calling be the last? It seems it suspends execution of following commands.
	stopRefreshAnim();
}

/*
* Backside events
*/

function setIdent() {
	var obj = document.getElementById('name_input');
	widget.setPreferenceForKey(obj.value, 'id');
}

function setPassword() {
	var obj = document.getElementById('pwd_input');
	widget.setPreferenceForKey(obj.value, 'pwd');
}

function setChelloPack(elem) {
	var chosenOption = elem.options[elem.selectedIndex].value;
	
	// display selection in front
	document.getElementById("tx_packname").innerText = PACKS[getIndexForPack(chosenOption)].display;

	// Other code that handles the menu selection change
	widget.setPreferenceForKey(chosenOption, 'pack');
}

// returns default Chello package name
function getDefaultPack() {
	var p = widget.preferenceForKey('pack');
	if (p == null) {
		// set default if not set yet
		p = PACKS[PACK_DEFAULT].name;
		widget.setPreferenceForKey(p, 'pack');
	} else {
		// convert old pack name to new
		if (p == "light") {
			p = "minimum";
			widget.setPreferenceForKey(p, 'pack');
		} else if (p == "standard") {
			p = "medium";
			widget.setPreferenceForKey(p, 'pack');
		} else if (p == "classic") {
			p = "extreme";
			widget.setPreferenceForKey(p, 'pack');
		} else if (p == "plus") {
			p = "professional";
			widget.setPreferenceForKey(p, 'pack');
		}
	}
	return p;
}

function getIndexForPack(name)
{
	if (name == null)
	return -1;

	var k = 0;
	for (i=0; i<PACKS.length; i++)
	{
		if (PACKS[i].name == name) {
			return k;
		}
		k++;
	}
	return -1;
}

// reset info
function reset() {
	var bar = document.getElementById('traffic_bar');

	bar.style.visibility = "hidden";

	document.getElementById('tx_traffic').style.color = "#FFFFFF";
	document.getElementById('tx_traffic').innerText = "-";

	// set pack limit
	var ix = getIndexForPack(getDefaultPack());
	if (ix != -1) {
		document.getElementById('tx_packname').innerText = PACKS[ix].display;
		document.getElementById('tx_limit').innerText = String(PACKS[ix].max / 1024) + " GB";
	} else {
		document.getElementById('tx_packname').innerText = "??";
		document.getElementById('tx_limit').innerText = "?? GB";
	}

	// marker button
	var p = widget.preferenceForKey('marked_data');
	if (p == null) {
		document.getElementById('marker_button').src = RES_IMAGES_PREFIX + "marker_on.png";
	} else {
		document.getElementById('marker_button').src = RES_IMAGES_PREFIX + "marker_off.png";
	}
}

function setTraffic(actual)
{
	var bar = document.getElementById('traffic_bar');
	var w;
	var px = OFFSET;

	//FIXME: adjust traffic bar
	var ix = getIndexForPack(getDefaultPack());

	// var max_chello = 30720.0; //30*1024
	var max_chello = PACKS[ix].max;
	if (actual > max_chello) {
		w = (max_chello * MAX_WIDTH) / actual;

		px = OFFSET + w;
		w = MAX_WIDTH - w;
		document.getElementById('tx_traffic').style.color = "#800000";
	} else {
		w = (actual * MAX_WIDTH) / max_chello;
		document.getElementById('tx_traffic').style.color = "#FFFFFF";
	}

	bar.src = RES_IMAGES_PREFIX + "ribbon_red.png";
	bar.style.left = px + "px";
	bar.width = w;
	bar.height = 21 /*12*/;
	bar.style.visibility = "visible";

	if (actual == 0) {
		document.getElementById('tx_traffic').innerText = "0 MB (0\%)";
	} else {
		document.getElementById('tx_traffic').innerText = actual + " MB (" + ((actual * 100) / max_chello).toFixed(1) + "\%)";
	}
	// set pack limit
	document.getElementById('tx_packname').innerText = PACKS[ix].display;
	document.getElementById('tx_limit').innerText = String(PACKS[ix].max / 1024) + " GB";
}



/*
* Mouse events
*/


function on_showSite() {
	widget.openURL('https://traffic.bpcl.broadband.hu/login.php');
}



function on_refresh() {
	doMainTask();
}



function on_mark() {

}



/*
 * Refresh animation
 */

var refresh_anim = {firstElement:null, timer:null, phase:0};

function startRefreshAnim() {
	if (refresh_anim.timer != null)
	{
		clearInterval(refresh_anim.timer);
		refresh_anim.timer  = null;
	}

	refresh_anim.firstElement = document.getElementById('refresh_button');
	refresh_anim.timer = setInterval("doAnimateRefresh();", 250);
	refresh_anim.phase = 0;
	doAnimateRefresh();
}

function stopRefreshAnim() {
	if (refresh_anim.timer != null)
	{
		clearInterval(refresh_anim.timer);
		refresh_anim.timer  = null;
	}
	document.getElementById('refresh_button').src = RES_IMAGES_PREFIX + "refresh.png";
}


function doAnimateRefresh() {
	
	refresh_anim.firstElement.src = RES_IMAGES_PREFIX + "refresh" + refresh_anim.phase + ".png";
	refresh_anim.phase = (refresh_anim.phase + 1) % 5;
}



/*
* New Version Management
*/

function checkNewVersion() {
	xmlhttp=new XMLHttpRequest();
	xmlhttp.setRequestHeader("Cache-Control", "no-cache");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4) {
			if (xmlhttp.status==200) {
				var site_ver = xmlhttp.responseText.replace(/\s+$/g, "");

				if (current_ver == site_ver) {
					document.getElementById("nv_frame").style.visibility = "hidden";
				} else {
					document.getElementById("current_label").innerText = site_ver;
					document.getElementById("nv_frame").style.visibility = "visible";
				}
			}
		}
	};

	// FIXME: ref: http://en.wikipedia.org/wiki/XMLHTTP#Microsoft_Internet_Explorer_Cache_issues
	// var ranNum = Math.round(Math.random()*4);
	var ranNum = Math.round(Math.random()*(new Date()).getTime());
	var url = "http://chellotraffic.googlecode.com/files/version.txt?" + ranNum;
	xmlhttp.open("GET", url, false);
	xmlhttp.send();
}



/*
 *
 */
if (window.widget)
{
	widget.onremove = remove;
	widget.onhide = hide;
	widget.onshow = show;
}
